<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加部门</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-form
        ref="addform"
        :rules="rules"
        label-width="80px"
        size="mini"
        :model="addform"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="部门名称:">
              <el-input v-model="addform.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="详细描述:">
              <el-input v-model="addform.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="2">
            <el-form-item>
              <el-button type="primary" size="small" @click="addbtn(addform)"
                >添加</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-form-item>
              <el-button type="warning" size="small" @click="goback">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addform: {
        id: "",
        name: "",
        remark: "",
      },
      rules: {
        name: [
          { required: true, trigger: "blur" },
          {
            min: 3,
            max: 5,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        remark: [
          { required: true, trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    async addbtn() {
      // 先进行表单验证
      this.$refs.addform.validate(async(valid) => {
        if (valid) {
          // 发送请求
          const {data:res} = await this.$http.post("/dept/add", this.addform);
          console.log(res);
          if (res.code === 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.$router.push("/deptlist");
          } else {
            this.$message.error("部门名称已存在");
          }
          
        } else {
          this.$message.error("表单验证失败，请检查输入"); // 提示用户
          return false;
        }
      });
    },
    goback() {
      window.history.back();
    },
  },
};
</script>

<style></style>
